<?php

namespace app\modules\client\controllers;

use Yii;
use yii\web\Controller;
use app\libraries\Common;
use app\libraries\Curl;

class ClientController extends Controller{

    public $enableCsrfValidation = false;

    public function actionIndex(){
        return $this->renderPartial("index");
    }

    public function actionRequest(){

        $id = isset($_GET["id"]) ? addslashes($_GET["id"]) : 0;
        $uri = isset($_GET["uri"]) ? addslashes($_GET["uri"]) : "";

        echo $uri;

        return $this->renderPartial('detail');
    }

    public function actionAuthorizeCode(){
        $params = Yii::$app->params;
        $data = [
            "gate" => $params["oauth2"]["authorize"],
        ];

        return $this->renderPartial("authorizeCode", $data);

    }

    /**
     * 先获取authorization_code再换取TOKEN，两步合一
     */
    public function actionAuthorize(){
        $params = Yii::$app->params;
        $data = [
            "gate" => $params["oauth2"]["authorize"],
        ];

        return $this->renderPartial("authorize", $data);

    }

    /**
     * 先获取authorization_code再换取TOKEN，两步合一
     */
    public function actionAsyncAuthorize(){
        $client_id = isset($_POST["client_id"]) ? addslashes($_POST["client_id"]) : "";
        $client_secret = isset($_POST["client_secret"]) ? addslashes($_POST["client_secret"]) : "";


        $params = Yii::$app->params;

        $gate = $params["oauth2"]["authorize"];

        $gate2 = $gate."?response_type=code&client_id=testclient&state=xyz";

        $data = [
            'authorized'=>'yes',
            'response_type'=>'code',
            'client_id'=>'testclient',
            'state'=>'xyz',
        ];
        
        $result = Curl::post_formdata($gate2, $data);

        //请在30秒内完成这个操作，因为Authorization Code的有效期只有30秒

        if($result_json = json_decode($result, true)){

            $authorization_code = $result_json["AuthorizationCode"]; 

            $data = [
                "grant_type" => 'authorization_code',
                "client_id" => $client_id,
                "client_secret" => $client_secret,
                "code" => $authorization_code,
            ];

            $result = Curl::post_formdata($params["oauth2"]["token"], $data);
            echo $result;

        }else{
            echo "JSON解析失败,原结果：".$result_json;
        }

    }

    public function actionProductList(){
        return $this->renderPartial("productList");
    }

}
